<?php
// +----------------------------------------------------------------------
// | Niucloud-admin 企业快速开发的多应用管理平台
// +----------------------------------------------------------------------
// | 官方网址：https://www.niucloud.com
// +----------------------------------------------------------------------
// | niucloud团队 版权所有 开源版本可自由商用
// +----------------------------------------------------------------------
// | Author: Niucloud Team
// +----------------------------------------------------------------------

namespace app\admin\service\order;

use app\core\exception\CommonException;
use app\dict\order\OrderDeliveryDict;
use app\dict\order\OrderDict;
use app\dict\order\OrderLogDict;
use app\api\model\order\Order;
use app\api\model\order\OrderDelivery;
use app\service\core\order\CoreOrderConsultService;
use app\service\core\order\CoreOrderFinishService;
use app\service\core\order\CoreOrderRefuseService;
use app\core\base\BaseApiService;

/**
 *  订单服务层
 */
class OrderService extends BaseApiService
{
     public function __construct()
     {
          parent::__construct();
          $this->model = new Order();
     }


     /**
      * 分页列表
      * @param array $where
      * @return array
      */
     public function getPage(array $where)
     {
          $field = ['order_id', 'order_no', 'order.status', 'goods_money', 'create_time', 'remark'];
          $order = 'create_time desc';
          $search_model = $this->model
               ->with(
                    [
                         'order_goods' => function ($query) {
                              $query->field('order_id,goods_id, sku_id, goods_name, sku_name, goods_image , price, num, goods_money');
                              $query->with(['card' => function ($query) {
                                   $query->field('id,sub_title,tags,rarity,ean');
                              }]);
                         },
                         'order_delivery' => function ($query) {
                              $query->field('order_id,send_name,send_mobile,send_full_address,express_number');
                              $query->where('type', 1);
                              $query->withJoin(['company' => ['company_name']]);
                         }
                    ]
               )
               ->withSearch(['order_no', 'join_status' => 'status', 'join_back_status_group', 'join_nickname' => 'nickname', 'join_mobile' => 'mobile'], $where)
               ->withJoin(['member' => ['nickname', 'headimg', 'mobile', 'member_id', 'member_no']])
               ->visible($field)->append(['status_name'])
               ->order($order);


          $list = $this->pageQuery($search_model);
          $list['list'] = $list['data'];
          unset($list['data']);
          //订单总数
          $list['count'] = $this->model->whereNotIn('status', [3, 4, 5])->count();
          //待查验
          $list['wait_check'] = $this->model->where('status', OrderDict::WAIT_CHECK)->count();
          //待协商
          $list['wait_consult'] = $this->model->where('status', OrderDict::WAIT_CONSULT)->count();
          //已完成
          $list['finish'] = $this->model->where('status', OrderDict::FINISH)->count();
          return $list;
     }

     /**
      * 详情
      * @param int $order_id
      * @return array
      */
     public function getDetail(int $order_id)
     {
          $field = 'order_id,order_no,status,goods_money,consult_money,create_time,is_consult,shop_remark,unboxing_video';
          $info = $this->model->where([['order_id', '=', $order_id]])->field($field)
               ->with(
                    [
                         'order_goods' => function ($query) {
                              $query->field('order_id, goods_id, sku_id, goods_name, sku_name, goods_image, price, num, goods_money')->append(['goods_image_thumb_small']);
                              $query->with(['card' => function ($query) {
                                   $query->field('id,sub_title,tags,rarity,ean');
                              }]);
                         },
                         'order_delivery' => function ($query) {
                              $query->field('order_id,send_name,send_mobile,send_full_address,express_number');
                              $query->where('type', 1);
                              $query->withJoin(['company' => ['company_name']]);

                         },
                    ]
               )->append(['status_name'])->findOrEmpty()->toArray();

          return $info;
     }


     /**
      * 订单审核
      * @param $data
      * @return void
      */
     public function check($data)
     {
          $where = array(
               ['order_id', '=', $data['id']],
               ['status', '=', OrderDict::WAIT_CHECK]
          );
          $order = $this->model->with('order_goods')->where($where)->findOrEmpty()->toArray();

          if (empty($order)) throw new CommonException('订单不存在或者非待查验单');//订单不存在
          $afterData = [
               'main_type' => OrderLogDict::STORE,
               'order_id' => $data['id'],
               'main_id' => $data['auth_id']
          ];

          if ($data['type'] == 1) {
               // 直接收货
               (new CoreOrderFinishService())->finish($order, $afterData, $data);
          } elseif ($data['type'] == 2) {
               // 拒绝
               (new CoreOrderRefuseService())->refuse($order, $afterData, $data);

          } elseif ($data['type'] == 3) {
               // 协商
               if ($data['consult_money'] > $order['goods_money']) throw new CommonException('协商金额不能大于订单金额');
               (new CoreOrderConsultService())->consult($order, $afterData, $data);

          }
          return 'SUCCESS';


     }

     /**
      * 物流信息
      * @param $id
      */
     public function getDeliveryPackage($data)
     {
          $field = 'id, order_id, name, delivery_type, sub_delivery_type, express_company_id, express_number, local_deliver_id, status, create_time';
          $info = (new OrderDelivery())->where([['id', '=', $data['id']]])->with([
               'company' => function ($query) {
                    $query->field('company_id, company_name, express_no');
               },
               'order_goods' => function ($query) {
                    $query->field('goods_name, sku_name, goods_image, delivery_id, num, price')->append(['goods_image_thumb_small']);
               }
          ])->field($field)->findOrEmpty()->toArray();

          if (!empty($info) && $info['delivery_type'] == OrderDeliveryDict::EXPRESS && $info['sub_delivery_type'] != OrderDeliveryDict::NONE_EXPRESS) {
               $info['mobile'] = $data['mobile'];
               $info = (new CoreOrderService())->deliverySearch($info);
               return $info;
          }
          return $info;
     }
}
